﻿using System.Linq;
using System.Threading.Tasks;
using HuiLian.Common;
using HuiLian.Common.Attributes;
using HuiLian.Common.Auth;
using HuiLian.Service.Platform.User;

namespace HuiLian.Web.Auth
{
    /// <summary>
    /// 权限处理
    /// </summary>
    [SingleInstance]
    public class PermissionHandler : IPermissionHandler
    {
        private readonly IUser _user;
        private readonly IUserService _userService;

        public PermissionHandler(IUserService userService, IUser user)
        {
            _user = user;
            _userService = userService;
        }

        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="api">接口路径</param>
        /// <param name="httpMethod">http请求方法</param>
        /// <returns></returns>
        public async Task<bool> ValidateAsync(string api, string httpMethod)
        {
            if (_user?.Name == "admin")
            {
                return true;
            }

            var permissions = await _userService.GetPermissionsAsync();

            //var isValid = permissions.Any(m => m.EqualsIgnoreCase($"{httpMethod}/{api}"));
            var isValid = permissions.Any(m => m != null && m.EqualsIgnoreCase($"/{api}"));
            return isValid;
        }
    }
}
